package com.cardone.platform.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cardone.common.router.support.RouterKeySupport;
import com.cardone.context.ContextHolder;
import com.cardone.platform.authority.service.AuthorityService;
import com.cardone.platform.configuration.service.ConfigurationService;

/**
 * @author yaoht
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CardoneHandlerInterceptor extends HandlerInterceptorAdapter implements AsyncHandlerInterceptor {
	private static final String VIEW_NAME_PREFIX = "default";

	private AuthorityService authorityService;

	private ConfigurationService configurationService;

	private RouterKeySupport routerKeySupport;

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
	        final Exception ex) throws Exception {
	}

	@Override
	public void afterConcurrentHandlingStarted(final HttpServletRequest request, final HttpServletResponse response,
	        final Object handler) throws Exception {
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
	        final ModelAndView modelAndView) throws Exception {
		if (modelAndView == null) {
			return;
		}

		String viewName = modelAndView.getViewName();

		if (StringUtils.isNotBlank(viewName)) {
			viewName = CardoneHandlerInterceptor.VIEW_NAME_PREFIX + viewName;

			modelAndView.setViewName(viewName);
		}
	}

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
	        throws Exception {
		ContextHolder.setId(request.getSession().getId());

		final String servletPath = request.getServletPath();

		if (StringUtils.startsWith(servletPath, "/resources")) {
			return true;
		}

		this.routerKeySupport.setGroupId(ContextHolder.getId(), "dev");

		// final String domainUrl = request.getServerName();

		return true;
	}
}
